import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse } from '@nestjs/websockets';
import { Messages } from 'protobuf/Messages';
import { Room } from 'src/class/room';
import { CodeEnum } from 'src/enum/CodeEnum';
import { roomManager } from 'src/manager/room-manager';
import { userManager } from 'src/manager/user-manager';
import WebSocket, { Server } from 'ws';

@WebSocketGateway(9021)
export class ChatGateway {

  @WebSocketServer()
  server: Server;

  private contectedSockets: {[key:number]:WebSocket} = {};

  async handleConnection(client: WebSocket): Promise<any>
  {
    let uid = Number(client.protocol);
    let user = userManager.getUserByUid(uid);
    user.socket = client;
    
    this.contectedSockets[uid] = client;
  }

  async handleDisconnect(client: WebSocket): Promise<any> 
  {
    let uid = Number(client.protocol);
    let user = userManager.getUserByUid(uid);
    user.socket = null;

    delete this.contectedSockets[uid];
  }

  private createWsResponse<T>(event: string, data: T)
  {
    let response: WsResponse<T> = {
      event: event,
      data: data,
    };
    
    return response;
  }

  @SubscribeMessage('createRoom')
  handleMessage(@MessageBody() data: any, @ConnectedSocket() client: WebSocket) 
  {
    let createRoomRequest = Messages.CreateRoomRequest.decode(data);
    let room = new Room();
    room.id = roomManager.createNewRoomId();
    room.ownerId = createRoomRequest.uid;
    room.allUser.push(userManager.getUserByUid(createRoomRequest.uid));
    roomManager.createRoom(room);

    let responseData: Messages.ICreateRoomResponse = {
      code: CodeEnum.success,
      roomId: room.id,
    };

    let buffer = Messages.CreateRoomResponse.encode(responseData).finish();

    client.send(JSON.stringify(this.createWsResponse('createRoom', buffer)));
  }
}
